<template>
  <CardItem class="mt-6" itemName="快速速报" :has-history="false">
    <template #real>
      <Table
        :dataSource="dataSource"
        :columns="quickReportColumns"
        :pagination="false"
        :customRow="setRowStyle"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'operation'">
            <Button type="link" style="color: #6ad7ca" @click="handleFlashPush"
              >推送</Button
            >
          </template>
        </template>
      </Table>
    </template>
  </CardItem>
  <CardItem itemName="快速预警" :has-history="false">
    <template #real>
      <Table
        :dataSource="dataSourceWarning"
        :columns="quickWarningColumns"
        :pagination="false"
        :customRow="setRowStyle"
      >
        <template #headerCell="{ column }">
          <template v-if="column.dataIndex === 'warningConfigName'">
            <span>
              <FormOutlined />
              {{ column.title }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'countdown'">
            <span>
              <FormOutlined />
              {{ column.title }}
            </span>
          </template>
        </template>
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'warningConfigName'">
            <div class="editable-cell">
              <div
                v-if="editWarningConfigName[record.warningLevelColor]"
                class="editable-cell-input-wrapper"
              >
                <Select
                  v-if="editWarningConfigName[record.warningLevelColor]"
                  :style="{ width: '120px' }"
                  v-model:value="
                    editWarningConfigName[record.warningLevelColor]
                      .warningConfigName
                  "
                  :options="warmList"
                ></Select>
              </div>
              <div v-else class="editable-cell-text-wrapper">
                <span @click="onWarningConfigName(record.warningLevelColor)">{{
                  text || '自动规则 '
                }}</span>
              </div>
            </div>
          </template>

          <template v-if="column.dataIndex === 'countdown'">
            <div class="editable-cell">
              <div
                v-if="editCountdown[record.warningLevelColor]"
                class="editable-cell-input-wrapper"
              >
                <Select
                  v-if="editCountdown[record.warningLevelColor]"
                  :style="{ width: '120px' }"
                  v-model:value="
                    editCountdown[record.warningLevelColor].warningConfigName
                  "
                  :options="timeOptions"
                ></Select>
              </div>
              <div v-else class="editable-cell-text-wrapper">
                <span @click="onCountdown(record.warningLevelColor)">{{
                  record.countdown
                }}</span>
              </div>
            </div>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <Button type="link" @click="_handlePush(record, '2')">推送</Button>
            <Button
              v-if="record.warningConfigName != null"
              type="link"
              @click="_handlePush(record, '4')"
              >低音推送</Button
            >
          </template>
        </template>
      </Table>
    </template>
  </CardItem>
  <CardItem itemName="快速气象" :has-history="false">
    <template #real>
      <Table
        :dataSource="dataSourceWeather"
        :columns="quickWeatherColumns"
        :pagination="false"
        :customRow="setRowStyle"
      >
        <template #headerCell="{ column }">
          <template v-if="column.dataIndex === 'typeCode'">
            <span>
              <FormOutlined />
              {{ column.title }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'hour'">
            <span>
              <FormOutlined />
              {{ column.title }}
            </span>
          </template>
        </template>
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'typeCode'">
            <div class="editable-cell">
              <div
                v-if="editTypeCode[record.levelCode]"
                class="editable-cell-input-wrapper"
              >
                <Select
                  v-if="editTypeCode[record.levelCode]"
                  :style="{ width: '120px' }"
                  v-model:value="editTypeCode[record.levelCode].typeCode"
                  :options="typeCodeOption"
                ></Select>
              </div>
              <div v-else class="editable-cell-text-wrapper">
                <span @click="onTypeCode(record.levelCode)">{{
                  text || '随机 '
                }}</span>
              </div>
            </div>
          </template>

          <template v-if="column.dataIndex === 'hour'">
            <div class="editable-cell">
              <div
                v-if="editHour[record.levelCode]"
                class="editable-cell-input-wrapper"
              >
                <Select
                  v-if="editHour[record.levelCode]"
                  :style="{ width: '120px' }"
                  v-model:value="editHour[record.levelCode].hour"
                  :options="weatherHourOptions"
                ></Select>
              </div>
              <div v-else class="editable-cell-text-wrapper">
                <span @click="onHour(record.levelCode)">{{
                  text || '随机 '
                }}</span>
              </div>
            </div>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <Button type="link" @click="handleWeatherPush(record)">推送</Button>
          </template>
        </template>
      </Table>
    </template>
  </CardItem>
  <!-- 推送验证码Modal -->
  <Modal
    v-model:open="open"
    width="30%"
    :mask-closable="false"
    :title="title"
    :keyboard="false"
    centered
    destroy-on-close
  >
    <div class="card-container">
      <div class="code-box">
        <Input v-model:value="messCode" placeholder="请输入验证码"> </Input>
        <span class="code-span" @click="getCode" v-if="!codeShow"
          >获取验证码</span
        >
        <span class="code-span" v-else>{{ codeTime }}s</span>
      </div>
    </div>
    <template #footer>
      <Button @click="submit">验证</Button>
    </template>
  </Modal>
  <!-- 推送Modal -->
  <Modal
    v-model:open="pushScheduleOpen"
    width="30%"
    :mask-closable="false"
    title="推送进度"
    :keyboard="false"
    centered
    destroy-on-close
  >
    <div class="card-container">
      <div class="push-header">
        <Progress
          type="circle"
          v-show="+num.toFixed(0) !== 100"
          :percentage="+num.toFixed(0)"
        ></Progress>
        <Result
          status="success"
          v-show="Number(num.toFixed(0)) == 100"
          title="推送完成"
        ></Result>
      </div>
    </div>
    <template #footer>
      <Button @click="pushClose">返回列表</Button>
    </template>
  </Modal>
</template>
<script setup lang="tsx">
import { UnwrapRef, reactive, ref } from 'vue';
import { FormOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Input,
  Modal,
  Progress,
  Result,
  Select,
  Table,
  message,
} from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { listToOption } from '@/utils/utils';
import { checkVerityCode, getCheckCode } from '@/api/device';
import {
  cancelFastWarning,
  cancelWeather,
  fastWeather,
  getAddress,
  getEewPushIndex,
  getFastWarning,
  getPushIndex,
  handleAdd,
  handleEewPush,
  handlePush,
  listLevelWarm,
  pushLogWeather,
  pushWeather,
} from '@/api/push';
import { weatherEnum } from '../contants/index';
import CardItem from './comm/CardItem.vue';

interface Props {
  pageData: any;
}
const props = defineProps<Props>();

//========================快速速报=======================
const dataSource = [
  {
    locname: '随机',
    magnitude: '随机',
    focdepth: '随机',
  },
];

// 设置速报行高
const setRowStyle = () => {
  return {
    style: {
      height: '30px', // 设置行高
      lineHeight: '30px', // 让内容垂直居中
    },
  };
};

const quickReportColumns = [
  {
    title: '位置',
    dataIndex: 'locname',
    key: 'locname',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '震级',
    dataIndex: 'magnitude',
    key: 'magnitude',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '震深',
    dataIndex: 'focdepth',
    key: 'focdepth',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'center' as const,
    width: '25%',
  },
];

const open = ref(false);
const codeTime = ref(0);
const codeShow = ref(false);
const timer1 = ref(0);
const messCode = ref('');
const title = ref('');
const handleFlashPush = () => {
  open.value = true;
  codeTime.value = 60;
  codeShow.value = false;
  clearInterval(timer1.value);
  timer1.value = 0;
  messCode.value = '';
  title.value = '快速速报';
};
// 推送后返回列表
const pushClose = () => {
  pushScheduleOpen.value = false;
};

/**
 * 获取验证码
 */
const getCode = async () => {
  let resCode = await getCheckCode({
    type: '1',
    code: props.pageData.code,
  });
  if (resCode.code == 200) {
    timer1.value = setInterval(() => {
      if (codeTime.value <= 0) {
        clearInterval(timer1.value);
        codeShow.value = false;
        codeTime.value = 60;
        return;
      }

      codeShow.value = true;
      codeTime.value--;
    }, 1000);
  }
};

/**
 * 验证码校验
 */
const rowWeatherData = ref<any>({});
const rowWarnData = ref<any>({});
const typeWarn = ref('');
const num = ref(0);
const timer = ref(0);
const submit = () => {
  checkVerityCode({
    verityCode: messCode.value,
    type: '1',
    code: props.pageData.code,
  }).then((res) => {
    if (res.code == 200) {
      open.value = false;
      message.success('验证码正确');
      if (title.value == '快速气象') {
        weatherDrill(rowWeatherData.value);
      } else if (title.value == '快速预警') {
        warnDrill(rowWarnData.value, typeWarn.value);
      } else {
        num.value = 0;
        timer.value = setInterval(() => {
          if (num.value >= 95) {
            return;
          }
          num.value += 5;
        }, 100);
        getRandomChinaCoordinate();
      }
    } else {
      message.error('验证码错误');
    }
  });
};

const formatlevel = (val: string) => {
  switch (val) {
    case '蓝色预警':
      return '01';
    case '黄色预警':
      return '02';
    case '橙色预警':
      return '03';
    case '红色预警':
      return '04';
    default:
      break;
  }
};
const weatherDrill = async (row: any) => {
  let param = {
    deviceId: props.pageData.deviceId,
    levelCode: formatlevel(row.levelCode),
  };
  if (row.typeCode == '随机') {
    let _code = Math.ceil(Math.random() * 14);
    console.log(_code, '_code');
    param.typeCode = _code >= 10 ? _code : '0' + _code;
  } else {
    param.typeCode = weatherEnum[row.typeCode as keyof typeof weatherEnum];
  }
  if (row.hour == '随机') {
    param.hour = (Math.random() * 23 + 1).toFixed(0);
  } else {
    param.hour = row.hour;
  }
  num.value = 0;
  pushScheduleOpen.value = true;
  timer.value = setInterval(() => {
    if (num.value >= 95) {
      return;
    }
    num.value += 5;
  }, 100);

  const res: any = await fastWeather(param);
  if (res.code == 200) {
    const res1 = await pushWeather({
      weatherWarningId: res.data.id,
    });
    if (res1.code == 200) {
      const res2 = await pushLogWeather({
        weatherWarningId: res.data.id,
        code: props.pageData.code,
        deviceId: props.pageData.deviceId,
        drillPushTotalId: res1.data,
      });
      clearInterval(timer.value);
      timer.value = 0;
      if (res2.code == 200) {
        num.value = 100;
      }
    }
  }
};

const warnDrill = async (row: any, type: any) => {
  let param = {
    msgType: type,
    deviceId: props.pageData.deviceId,
    warningConfigName: row.warningConfigName,
    warningLevelColor: row.warningLevelColor,
    countdown: row.countdown,
  };
  if (row.countdown == '随机') {
    param.countdown = (Math.random() * 10 + 20).toFixed(0);
  } else {
    param.countdown = row.countdown;
  }

  const res: any = await getFastWarning(param);
  if (res.code == 200) {
    num.value = 0;
    pushScheduleOpen.value = true;
    timer.value = setInterval(() => {
      if (num.value >= 95) {
        return;
      }
      num.value += 5;
    }, 100);
    const res1: any = await getPushIndex({ msgId: res.data.msgId });
    if (res1.code == 200) {
      const res2 = await handlePush([
        {
          msgId: res.data.msgId,
          code: props.pageData.code,
          deviceId: props.pageData.deviceId,
          drillPushTotalId: res1.data,
        },
      ]);
      clearInterval(timer.value);
      timer.value = 0;
      if (res2.code == 200) {
        num.value = 100;
      }
    }
  }
};

// 随机生成中国经纬度
const getRandomChinaCoordinate = () => {
  // 中国经度范围
  var minLng = 90;
  var maxLng = 120;
  // 中国纬度范围
  var minLat = 15;
  var maxLat = 50;
  // 生成随机经度
  var longitude = (Math.random() * (maxLng - minLng) + minLng).toFixed(6);
  // 生成随机纬度
  var latitude = (Math.random() * (maxLat - minLat) + minLat).toFixed(6);
  _getAddress(longitude, latitude);
};
const paramData = ref<any>({});

const formatIntensity = (val: number) => {
  if (val <= 1.5) {
    return 0;
  } else {
    return Math.floor((val - 1.5) / 0.58);
  }
};
const _getAddress = async (lon: any, lat: any) => {
  const res: any = await getAddress(lon, lat);
  if (res.code == 200) {
    if (res.msg == '' || res.msg == null) {
      return getRandomChinaCoordinate();
    }
    // 随机生成规则
    let magnitude = Math.random() * 3 + 3;
    let focdepth = Math.random() * 15 + 10;
    paramData.value = {
      epiintensity: formatIntensity(magnitude),
      epilon: lon,
      epilat: lat,
      locname: res.msg == '操作成功' ? '' : res.msg,
      deviceId: [props.pageData.deviceId],
      magnitude: magnitude.toFixed(1),
      focdepth: Math.ceil(focdepth),
    };
    _handleAdd();
  }
};

const pushScheduleOpen = ref(false);
const _handleAdd = async () => {
  const res: any = await handleAdd(paramData.value);
  pushScheduleOpen.value = true;
  if (res.code == 200) {
    _getPushIndex(res.data.msgId);
  }
};

const _getPushIndex = async (msgId: any) => {
  const res = await getEewPushIndex({ msgId: msgId });
  if (res.code == 200) {
    handlePush1(msgId, res.data);
  }
};

const handlePush1 = async (msgId: any, drillPushTotalId: any) => {
  const res = await handleEewPush({
    msgId: msgId,
    code: props.pageData.code,
    deviceId: props.pageData.deviceId,
    drillPushTotalId: drillPushTotalId,
  });
  clearInterval(timer.value);
  timer.value = 0;
  if (res.code == 200) {
    num.value = 100;
  }
};

//========================快速预警=======================
// 获取预警配置列表
const warmList = ref<Global.Option[]>([]); //预警配置列表
const _listLevelWarm = async () => {
  const res: any = await listLevelWarm();
  if (res.code == 200) {
    let obj = {
      name: '自动规则',
    };
    warmList.value = listToOption(res.data, 'name', 'name');
    warmList.value = warmList.value.filter(
      (item: any) => item.name !== '自动规则',
    );
    console.log(warmList.value, 'this.warmList');
  }
};
_listLevelWarm();

const timeOptions = ref<Global.Option[]>([]);
const timeList = ['随机', '15', '20', '25', '30', '60'];
timeOptions.value = timeList.map((item) => {
  return {
    label: item,
    value: item,
  };
});
const warnLevel = [
  '无预警',
  '蓝色预警',
  '黄色预警',
  '橙色预警',
  '红色预警',
  '取消预警',
];
const dataSourceWarning = [
  {
    warningConfigName: '',
    warningLevelColor: '无预警',
    countdown: '随机',
  },
  {
    warningConfigName: '',
    warningLevelColor: '蓝色预警',
    countdown: '随机',
  },
  {
    warningConfigName: '',
    warningLevelColor: '黄色预警',
    countdown: '随机',
  },
  {
    warningConfigName: '',
    warningLevelColor: '橙色预警',
    countdown: '随机',
  },
  {
    warningConfigName: '',
    warningLevelColor: '红色预警',
    countdown: '随机',
  },
  {
    warningConfigName: null,
    warningLevelColor: '取消预警',
    countdown: '',
  },
];

const quickWarningColumns = [
  {
    title: '设备响应等级',
    dataIndex: 'warningLevelColor',
    key: 'warningLevelColor',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '预警响应规则',
    dataIndex: 'warningConfigName',
    key: 'warningConfigName',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '倒计时',
    dataIndex: 'countdown',
    key: 'countdown',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'center' as const,
    width: '25%',
  },
];

// 选择预警响应规则
const editWarningConfigName: UnwrapRef<
  Record<
    string,
    {
      warningConfigName: string | null;
      warningLevelColor: string;
      countdown: string;
    }
  >
> = reactive({});
const editCountdown: UnwrapRef<
  Record<
    string,
    {
      warningConfigName: string | null;
      warningLevelColor: string;
      countdown: string;
    }
  >
> = reactive({});

// 推送
const _handlePush = async (record: any, type: string) => {
  if (record.warningLevelColor == '取消预警') {
    const rescancel = await cancelFastWarning(props.pageData.code);
    if (rescancel.code == 200) {
      message.success('取消预警成功');
    }
    return;
  }
  rowWarnData.value = record;
  typeWarn.value = type;
  open.value = true;
  codeTime.value = 60;
  codeShow.value = false;
  clearInterval(timer1.value);
  timer1.value = 0;
  messCode.value = '';
  title.value = '快速预警';
};

const onWarningConfigName = (key: string) => {
  console.log(
    key,
    dataSourceWarning.filter((item: any) => key === item.warningLevelColor)[0],
    'edit',
  );

  editWarningConfigName[key] = cloneDeep(
    dataSourceWarning.filter((item) => key === item.warningLevelColor)[0],
  );
  console.log(editWarningConfigName[key], 'editableData[key]');
};
const onCountdown = (key: string) => {
  console.log(
    key,
    dataSourceWarning.filter((item: any) => key === item.warningLevelColor)[0],
    'edit',
  );

  editCountdown[key] = cloneDeep(
    dataSourceWarning.filter((item) => key === item.warningLevelColor)[0],
  );
  console.log(editCountdown[key], 'editableData[key]');
};

//========================快速气象=======================
const weatherHourOptions = ref<Global.Option[]>([]);
const weatherHourList = ['随机', '1', '3', '6', '12', '24'];
weatherHourOptions.value = weatherHourList.map((item) => {
  return {
    label: item,
    value: item,
  };
});
const typeCodeList = [
  '随机',
  '台风',
  '暴雨',
  '暴雪',
  '寒潮',
  '大风',
  '沙尘暴',
  '高温',
  '干旱',
  '雷电',
  '冰雹',
  '霜冻',
  '大雾',
  '霾',
  '道路结冰',
];
const typeCodeOption = ref<Global.Option[]>([]);
typeCodeOption.value = typeCodeList.map((item) => {
  return {
    label: item,
    value: item,
  };
});

const dataSourceWeather = [
  { typeCode: '随机', levelCode: '蓝色预警', hour: '随机' },
  { typeCode: '随机', levelCode: '黄色预警', hour: '随机' },
  { typeCode: '随机', levelCode: '橙色预警', hour: '随机' },
  { typeCode: '随机', levelCode: '红色预警', hour: '随机' },
  { typeCode: '', levelCode: '取消预警', hour: '' },
];

const quickWeatherColumns = [
  {
    title: '设备响应等级',
    dataIndex: 'levelCode',
    key: 'levelCode',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '气象类型',
    dataIndex: 'typeCode',
    key: 'typeCode',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '有效期(小时)',
    dataIndex: 'hour',
    key: 'hour',
    align: 'center' as const,
    width: '25%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'center' as const,
    width: '25%',
  },
];
// 编辑气象类型
const editTypeCode: UnwrapRef<
  Record<
    string,
    {
      levelCode: string | null;
      typeCode: string;
      hour: string;
    }
  >
> = reactive({});
// 编辑有效期(小时)
const editHour: UnwrapRef<
  Record<
    string,
    {
      levelCode: string | null;
      typeCode: string;
      hour: string;
    }
  >
> = reactive({});

/**
 * 选择气象类型
 * @param key
 */
const onTypeCode = (key: string) => {
  editTypeCode[key] = cloneDeep(
    dataSourceWeather.filter((item) => key === item.levelCode)[0],
  );
  console.log(editTypeCode[key], 'editTypeCode[key]');
};
/**
 * 选择有效期(小时)
 * @param key
 */
const onHour = (key: string) => {
  editHour[key] = cloneDeep(
    dataSourceWeather.filter((item) => key === item.levelCode)[0],
  );
  console.log(editHour[key], 'editHour[key]');
};

const handleWeatherPush = async (record: any) => {
  if (record.levelCode == '取消预警') {
    const rescancel = await cancelWeather(props.pageData.code);
    if (rescancel.code == 200) {
      message.success('取消预警成功');
    }
    return;
  }
  open.value = true;
  codeTime.value = 60;
  codeShow.value = false;
  clearInterval(timer1.value);
  timer1.value = 0;
  messCode.value = '';
  rowWeatherData.value = record;
  title.value = '快速气象';
};
</script>
<style lang="scss" scoped>
.code-box {
  position: relative;
  & > input {
    background: transparent;
  }
  .code-span {
    position: absolute;
    right: 10px;
    top: 8px;
    color: #0095ff;
    cursor: pointer;
  }
}

.push-header {
  display: flex;
  justify-content: center;
}
</style>
